import Axios from 'axios'
import qs from 'qs'
 
Axios.defaults.timeout = 60000
// Axios.defaults.baseURL = 'http://localhost:8080'
 
 
Axios.interceptors.request.use(
  config => {
    if(config.method === 'post') { //支持2种方法，默认使用Form Data
      if(config.data.useRequestBody) {
        //参数需要带上useRequestBody
        //如果useRequestBody=true, 支持Request Payload，
        //SpringMVC Controller 中需要使用@RequestBody
        delete config.data.useRequestBody;
        config.headers = {
          'Content-Type': 'application/json;charset=UTF-8'
        }
      } else { 
        //如果useRequestBody=false, 默认支持Form Data
        //SpringMVC Controller 中不需要使用@RequestBody，默认使用@RequestParam
        config.data = qs.stringify(config.data); 
        config.headers = {
          'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'
        }
      }
      
    } else if(config.method === 'get') {
      let newParams = {}
      for(let key in config.params) {
        newParams[key] = encodeURIComponent(config.params[key])
      }
      config.params = newParams
 
      config.headers = {
        'Content-Type': 'application/json;charset=UTF-8'
      }
    }
    config.headers.Authorization = window.sessionStorage.getItem('token')
    return config
  },
  error => {
    return Promise.reject(error)
  }
)
 

 
/**
 * 封装get方法
 * @param url
 * @param data
 * @returns {Promise}
 */
 
const get = function get(url, params = {}) {
  return Axios.get(url, { params: params })
}
 
 
/**
 * 封装post请求
 * @param url
 * @param params
 * @returns {Promise}
 */
 
const post = function post(url, params = {}) {
  return Axios.post(url, params)
}
 
/**
 * 封装del请求
 * @param url
 * @param data
 * @returns {Promise}
 */
 
const del = function del(url, data = {}) {
  return Axios.delete(url, data)
}
 
/**
 * 封装put请求
 * @param url
 * @param data
 * @returns {Promise}
 */
 
const put = function put(url, data = {}) {
  return Axios.put(url, data)
}
 
 
export default {
  post,
  get,
  del,
  put
}